const cp = require("child_process")
const { resolve } = require("path")
const mongoose = require("mongoose")
const Movie = mongoose.model('Movie')

    ; (async () => {
        const script = resolve(__dirname, "../crawler/trailer-list")

        const child = cp.fork(script, [])

        let invoked = false

        child.on('error', err => {
            if (invoked) return
            invoked = true
            console.log(err)
        })
        child.on("exit", code => {
            if (invoked) return
            else invoked = true

            let err = code === 0 ? null : new Error('exit code' + code)
            console.log(err)
        })
        //时间监听
        child.on('message', data => {
            let result = data.result
            console.log(result)
            result.forEach(async element => {
                let movie = await Movie.findOne({
                    doubanID:element.doubanID
                })
                if (!movie){
                    movie = new Movie(element)
                    await movie.save()
                }
            });
            // process.send(result.)
        })
    })()